package com.tju.resource.oauth.controller;

import com.tju.resource.model.TbOrder;
import com.tju.resource.server.TbOrderService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.tool.ClientParameters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 订单
 */
@Slf4j
@RestController
public class TbOrderController {
    private static final String prefix = "order";

    @Autowired
    private TbOrderService tbOrderService;
    private Lock lock =new ReentrantLock(true); //安全锁
    /**
     * 查询订单
     */
    @PostMapping(prefix + "/getOrder")
    @PreAuthorize("hasAuthority('sys:order:list')")
    public Result<Object> list(@RequestBody ClientParameters parameter) {
        return tbOrderService.selectTbOrderList(parameter);
    }

    /**
     * 添加订单
     */
    @PostMapping(prefix + "/addOrder")
    @PreAuthorize("hasAuthority('sys:order:add')")
    public Result<Object> add(@RequestBody TbOrder tbOrder) {
        try {
            lock.lock();
            return tbOrderService.insertTbOrder(tbOrder);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally{
            lock.unlock();
        }
    }

    /**
     * 修改订单
     */
    @PostMapping(prefix + "/updateOrder")
    @PreAuthorize("hasAuthority('sys:order:edit')")
    public Result<Object> edit(@RequestBody TbOrder tbOrder) {
        try {
            lock.lock();
            return tbOrderService.updateTbOrder(tbOrder);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally{
            lock.unlock();
        }

    }

    /**
     * 删除订单
     */
    @PostMapping(prefix + "/deleteOrder")
    @PreAuthorize("hasAuthority('sys:order:delete')")
    public Result<Object> delete(@RequestBody TbOrder tbOrder)
    {
        try {
            lock.lock();
            return tbOrderService.deleteTbOrder(tbOrder);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally{
            lock.unlock();
        }

    }

    /**
     * 导出订单
     */
    @PostMapping(prefix + "/exportOrder")
    @PreAuthorize("hasAuthority('sys:order:export')")
    public Result<Object> exportOrder(@RequestBody ClientParameters parameter) {
        return tbOrderService.exportOrder(parameter);

    }
}
